package com.wenkang.stu.config.security.handler;

import com.wenkang.stu.pojo.SysUser;
import com.wenkang.stu.util.JwtUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AdminLoginSuccessHandler implements AuthenticationSuccessHandler {
    private static final String AUTHENTICATION_PREFIX = "Bearer ";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authResult) throws IOException, ServletException {
        // 验证成功，相应Jwt
        SysUser user = (SysUser) authResult.getPrincipal();
        String token = JwtUtils.generateToken(user);
        httpServletResponse.addHeader(HttpHeaders.AUTHORIZATION, AUTHENTICATION_PREFIX + token);
        httpServletResponse.addHeader("Access-Control-Expose-Headers", HttpHeaders.AUTHORIZATION);
    }
}
